<template>
<div>
    <a-button class="editable-add-btn" style="margin-bottom: 8px" type="primary" @click="handleAdd">发布商品</a-button>

    <a-table bordered :data-source="dataSource" :columns="columns">
        <template #img="{ text }">
            <img :src="text" width=150>
        </template>
        <template #type="{ text: type }">
            <span>
                <a-tag :color="TypeNumToTextMap[type].color">
                    {{ TypeNumToTextMap[type].text }}
                </a-tag>
            </span>
        </template>

        <template #bodyCell="{column, text, record }">
            <template v-if="['id', 'name','price','num','desc'].includes(column.dataIndex)">
                {{ text }}
            </template>
            <template v-else-if="['operation'].includes(column.dataIndex)">
                <a-space>
                    <a-popconfirm title="确定删除吗?" ok-text="是" cancel-text="否"
                        @confirm="onDelete(record.id)"
                    >
                        <a>删除</a>
                    </a-popconfirm>
                    <a @click="onEdit(record)">修改</a>
                </a-space>
            </template>
        </template>
    </a-table>

    <a-modal v-model:visible="visible" :title="modalStatus ? '修改商品' : '发布商品'" 
        @ok="handleOk" @cancel="handleCancel" okText="确定" cancelText="取消">

        <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" autocomplete="off">
            <a-form-item label="商品 id" name="id">
                <a-input v-model:value="formState.id" />
            </a-form-item>
            <a-form-item label="图片">
                <a-upload name="avatar" list-type="picture-card" class="avatar-uploader" >
                    <img :src="formState.img" width="100" v-if="formState.img">
                    <plus-outlined v-else></plus-outlined>
                </a-upload>
            </a-form-item>
            <a-form-item label="商品名称" name="name">
                <a-input v-model:value="formState.name" />
            </a-form-item>
            <a-form-item label="商品类别" name="type">
                <a-select v-model:value="formState.type">
                    <a-select-option :value="1">食品</a-select-option>
                    <a-select-option :value="2">医疗</a-select-option>
                    <a-select-option :value="3">日常用品</a-select-option>
                    <a-select-option :value="4">电子产品</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="价格" name="price">
                <a-input v-model:value="formState.price" />
            </a-form-item>
            <a-form-item label="数量" name="num">
                <a-input v-model:value="formState.num" />
            </a-form-item>
            <a-form-item label="说明" name="desc">
                <a-textarea v-model:value="formState.desc" />
            </a-form-item>
        </a-form>
    </a-modal>
</div>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import {getProductList, addProduct, deleteProduct, updateProduct } from '../../service/api/product';
import { message } from 'ant-design-vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { TypeNumToTextMap } from '../../utils/const';

// 表头
const columns = [{
    title: '商品 id',
    dataIndex: 'id',
}, {
    title: '图片',
    dataIndex: 'img',
    width: '150',
    slots: {
      customRender: 'img',
    },
}, {
    title: '商品名称',
    dataIndex: 'name',
}, {
    title: '商品类别',
    dataIndex: 'type',
    slots: {
      customRender: 'type'
    }
}, {
    title: '价格',
    dataIndex: 'price',
}, {
    title: '数量',
    dataIndex: 'num',
}, {
    title: '说明',
    dataIndex: 'desc',
}, {
    title: '操作',
    dataIndex: 'operation',
}];

// 数据源
let dataSource = ref();

const useHttpRequestEffect = () => {
    const getProductDataRequest = async () => {
        const res = await getProductList();
        dataSource.value = res?.data
    }
    const addProductRequest = async (data) => {
        const res = await addProduct(data);
        if (res?.data?.res) {
            message.success("添加成功")
        } else {
            message.error("添加失败")
        }
    }
    const deleteProductRequest = async (data) => {
        const res = await deleteProduct(data);
        if (res?.data?.res) {
            message.success("删除成功")
        } else {
            message.error("删除失败")
        }
    }
    const updateProductRequest = async (data) => {
        const res = await updateProduct(data);
        if (res?.data?.res) {
            message.success("修改成功")
        } else {
            message.error("修改失败")
        }
    }
    return {getProductDataRequest, addProductRequest, deleteProductRequest, updateProductRequest }
}

const useModalEffect = () => {
  const visible = ref(false);
  const formState = ref({});
  const modalStatus = ref(0); // 0新增 1编辑

  const { addProductRequest, deleteProductRequest, updateProductRequest } = useHttpRequestEffect();
  const onDelete = id => {
    dataSource.value = dataSource.value.filter(item => item.id !== id);
    deleteProductRequest(id);
  };
  const onEdit = item => {
    formState.value = item;
    modalStatus.value = 1;
    visible.value = true;
  };
  const handleAdd = () => {
    modalStatus.value = 0;
    visible.value = true;
  };
  const handleOk = () => {
    if (modalStatus.value === 0) {
      dataSource.value.push(formState.value);
      addProductRequest(formState.value);
    } else if (modalStatus.value === 1) {
      updateProductRequest(formState.value);
    }
    visible.value = false;
    formState.value = [];
  };
  const handleCancel = () => {
    visible.value = false;
    formState.value = [];
  }
    return {
        visible, formState, modalStatus,
        onEdit, onDelete, handleOk, handleCancel,
        handleAdd
    }
  }

export default defineComponent({
  components:{
    LoadingOutlined,
    PlusOutlined,
  },
  setup() {
    const {  getProductDataRequest } = useHttpRequestEffect();
    const {
        visible, formState, modalStatus,
        onEdit, onDelete, handleOk, handleCancel,
        handleAdd } = useModalEffect();
    onMounted(async () => {
      await getProductDataRequest();
    });

    return {
      columns,
      dataSource,
      getProductDataRequest,
      visible,
      formState,
      modalStatus,
      onEdit,
      onDelete,
      handleOk,
      handleCancel,
      handleAdd,
      TypeNumToTextMap
    };
  },
});
</script>

<style scoped>
.editable-add-btn{
    background-color: rgb(24, 144, 255);
    color:#fff;
}
.editable-add-btn:hover{
    background-color: rgb(24, 132, 234);
}
.editable-add-btn:active{
    background-color: rgb(117, 178, 236);
}
.editable-row-operations a {
  margin-right: 8px;
}
</style>